package math;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import model.AltaRicaNode;
import parser.AltaRicaParseNode;
import parser.AltaRicaParser;
import parser.ParseException;

import common.Relations;
import common.commands.ICommand.CommandValue;

public class Relation {
	
	private String id;
	
	private String base;
	private Expression expr;
	private AltaRicaNode node;
	
	public Relation() {
		id = null;
		base = null;
		expr = null;
		node = null;
	}
	
	public String getId() {
		return this.id;
	}
	
	public void setId(String id) {
		this.id = id;
	}
	
	public String getBase() {
		return this.base;
	}
	
	public void setBase(String base) {
		this.base = base;
	}
	
	public Expression getExpression() {
		return this.expr;
	}
	
	public void setExpression(Expression expr) {
		this.expr = expr;
	}
	
	public AltaRicaNode getNode() {
		return this.node;
	}
	
	public void setNode(AltaRicaNode node) {
		this.node = node;
	}
	
	public String toString() {
		
		return id + "( " + base + " : " + node.getName() + " ) := " + expr.toString() + ";";
	}
	
	public static CommandValue parseRelation(String str, Relation r) {
		
		InputStream in = new ByteArrayInputStream(str.getBytes());
		
		try {
			r = AltaRicaParser.parseRelation(in);
		} catch (ParseException e) {
			System.out.println("Error");
			return CommandValue.KO;
		}
		
		AltaRicaParseNode pnode = new AltaRicaParseNode();
		pnode.compileRelation(r);
		
		Relations.addRelation(r);
		
		return CommandValue.OK;
	}
}
